<template>
  <div v-if="pushInfo">
    <pushInfoCard @submit="submit" />
  </div>
</template>

<script setup>
import pushInfoCard from '../components/pushInfoCard.vue';
import { watch, ref, onMounted, onBeforeUnmount } from 'vue';
import { useUserStore } from '@/stores/user';
import { storeToRefs } from 'pinia';
import { useMap } from '@/stores/useMap.js';
const { map, draw } = storeToRefs(useMap());
const { setDraw } = useMap();
const { pushInfo, areaInfo } = storeToRefs(useUserStore());
const announcementData = ref([]);
import * as turf from '@turf/turf';
let source, vector, styles;
const info = ref([]);
const submit = data => {
  announcementData.value.push(data);
};
const getAnnouncement = () => {
  const annoList = JSON.parse(localStorage.getItem('annoList') || '[]');
  announcementData.value = annoList;
};
watch(
  announcementData,
  () => {
    if (announcementData.value.length) {
      localStorage.setItem('annoList', JSON.stringify(announcementData.value));
    }
  },
  { deep: true }
);
onMounted(() => {
  getAnnouncement();
});
// 创建新的绘制交互对象
const newDraw = new ol.interaction.Draw({
  source: source,
  type: 'LineString',
});
setDraw(newDraw); // 更新 draw 状态
newDraw.on('drawend', event => {
  const lineString = event.feature.getGeometry().getCoordinates();
  const data = getOriginData([lineString]);
  loadData(data);
});
//监听地图变化
watch(
  () => map.value,
  newMap => {
    if (newMap) {
      try {
        map.value.removeInteraction(draw.value);
        map.value.addInteraction(newDraw);
      } catch (error) {
       // console.error('初始化地图交互失败:', error);
      }
    }
  },
  { immediate: true }
);
//初始化缓冲区的样式
styles = {
  Polygon: new ol.style.Style({
    stroke: new ol.style.Stroke({
      color: 'green',
      lineDash: [4],
      width: 3,
    }),
    fill: new ol.style.Fill({
      color: 'rgba(255, 255, 153, 0.2)',
    }),
  }),
};
var styleFunction = function (feature) {
  return styles[feature.getGeometry().getType()];
};
//封装一个根据坐标位置数组生成json的方法
function getOriginData(arr) {
  let lineArr = [];
  for (let index = 0; index < arr.length; index++) {
    let feature = {
      type: 'Feature',
      properties: {},
      geometry: {
        type: 'LineString',
        coordinates: arr[index], // 直接赋值坐标数组
      },
    };
    lineArr.push(feature);
  }
  const tempJson = {
    type: 'FeatureCollection',
    crs: {
      type: 'name',
      properties: {
        name: 'EPSG:4326',
      },
    },
    features: lineArr,
  };
  return tempJson; //return JSON.stringify(tempJson, null, 2);//不要用stringify转成字符串,turf会报错
}
//生成缓冲区
function loadData(origindata) {
  source = new ol.source.Vector();
  var format = new ol.format.GeoJSON(); //console.log(origindata); //turf.buffer 是 Turf.js 提供的一个方法，用于创建一个缓冲区。这个方法接受三个参数： //第一个参数：要缓冲的 GeoJSON 特征或特征集合。 //第二个参数：缓冲区的距离。单位为千米 //第三个参数：一个选项对象，用于指定距离的单位和其他配置。
  var bufferJson = turf.buffer(origindata, 0.1, {
    units: 'miles',
  });
  let features = bufferJson.features; //获取缓冲区features
  for (var i = 0; i < features.length; i++) {
    let oljson = new ol.format.GeoJSON();
    let feature = oljson.readFeature(features[i]); //feature.getGeometry().transform('EPSG:4326', 'EPSG:3857');
    let geometry = feature.getGeometry();
    eventArea(geometry);
    source.addFeature(feature);
  }
  vector = new ol.layer.Vector({
    source: source,
    style: styleFunction,
  });
  vector.setZIndex(1001);
  map.value.addLayer(vector); //console.log('建立缓冲区over!');
  pushInfo.value = true;
}
function eventArea(data) {
  //1.初始化查询结构对象，设置查询结构包含几何信息
  var queryStruct = new Zondy.Service.QueryFeatureStruct();
  //是否包含几何图形信息
  queryStruct.IncludeGeometry = true;
  //是否包含属性信息
  queryStruct.IncludeAttribute = true;
  //是否包含图形显示参数
  queryStruct.IncludeWebGraphic = false;
  //创建一个用于查询的区
  var geomObj = new Zondy.Object.Polygon();
  geomObj.setByOL(data);
  //2.指定查询规则
  var rule = new Zondy.Service.QueryFeatureRule({
    //是否将要素的可见性计算在内
    EnableDisplayCondition: false,
    //是否完全包含
    MustInside: false,
    //是否仅比较要素的外包矩形
    CompareRectOnly: false,
    //是否相交
    Intersect: true,
  });
  //3.实例化查询参数对象
  var queryParam = new Zondy.Service.QueryParameter({
    geometry: geomObj,
    resultFormat: 'json',
    struct: queryStruct,
    rule: rule,
  });
  //设置查询分页号
  queryParam.pageIndex = 0;
  //设置查询要素数目
  queryParam.recordNumber = 100;
  //4.实例化地图文档查询服务对象
  var queryService = new Zondy.Service.QueryDocFeature(queryParam, 'guanggu', 0, {
    ip: 'localhost',
    port: '8089', //访问IGServer的端口号，.net版为6163，Java版为8089
  });
  //执行查询操作，querySuccess为查询回调函数
  queryService.query(querySuccess, queryError);
}
//查询失败回调
function queryError(e) {
  console.log(e);
}
//查询成功回调
function querySuccess(result) {
  info.value = result.SFEleArray;
  const a = info.value.map(item => {
    return [item.AttValue[3], item.AttValue[4]];
  });
  areaInfo.value = a;
}
onBeforeUnmount(() => {
  // 清理资源
  map.value.removeInteraction(draw.value);
  source.clear();
});
</script>

<style scoped></style>
